package com.linwen.javase.juc;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName _09SyncThread2
 * @Description
 * @Author lin
 * @Date 2022/4/21 上午12:45
 * @Version V1.0
 *
 *
 * synchronized锁的基本形式
 * 普通同步方法中：锁默认是当前对象
 * 静态方法中：锁默认是class对象
 * 方法块中：锁需要自行在synchronized中配置
 *
 * 公平锁和非公平锁
 * https://blog.csdn.net/CharlesYooSky/article/details/105238331?spm=1001.2101.3001.6661.1&utm_medium=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1.pc_relevant_antiscanv2&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1.pc_relevant_antiscanv2&utm_relevant_index=1
 *
 */
public class _09SyncThread2 {
    public static void main(String[] args) {
        SyncThread2 syncThread2 = new SyncThread2();
//        new Thread(()->{
//            syncThread2.test1();
//        }).start();
//        new Thread(()->{
//            syncThread2.test2();
//        }).start();
        new Thread(()->{
            syncThread2.test3();
        }).start();
        new Thread(()->{
            syncThread2.test4();
        }).start();
        new Thread(()->{
            syncThread2.test5();
        }).start();
    }
}

class SyncThread2{
    private int num = 0;
    private Lock lock = new ReentrantLock();
    public void test1(){
        synchronized (this){
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            num++;
            System.out.println("111    "+num);
        }
    }

    public void test2(){
        synchronized (this){
            num--;
            System.out.println("222   "+num);
        }
    }

    public  void test3(){
        System.out.println("333333");
    }

    public void test4(){
        lock.lock();
        try {
            Thread.sleep(2000);
            num++;
            System.out.println("444   "+num);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void test5(){
        lock.lock();
        try {
            num--;
            System.out.println("555   "+num);
        } finally {
            lock.unlock();
        }
    }

}

